from django.db import models
from django.contrib.auth import get_user_model
import hashlib
User = get_user_model()
# Create your models here.
class PrivateMessage(models.Model):
    key = models.CharField(max_length=64)
    sender = models.ForeignKey(User,on_delete=models.CASCADE,related_name='private_send_messages')
    receiver = models.ForeignKey(User, on_delete=models.CASCADE,related_name='private_receive_messages')
    content = models.TextField(max_length=500)
    timestamp = models.DateTimeField(auto_now_add=True)
    # is_read = models.BooleanField(default=False)

    class Meta:
        ordering = ['-timestamp']
        indexes = [
            models.Index(fields=['key','sender','receiver','timestamp'])
        ]

    def __str__(self):
        return f"{self.sender}->{self.receiver}:{self.timestamp}"


def get_room_key(u1, u2):
    ids = sorted([str(u1), str(u2)])
    return hashlib.sha256('-'.join(ids).encode('utf-8')).hexdigest()[:50]
class PrivateRoom(models.Model):
    key = models.CharField(max_length=64, unique=True)  # 两人唯一标识
    users = models.ManyToManyField(User,related_name='private_room')
